package cn.mumzone.pos.ui.adapter;

import android.content.Context;
import android.graphics.Typeface;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.BigDecimalUtil;
import cn.mumzone.basic.util.DisplayUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.model.ReserveEntity;
import cn.mumzone.pos.model.ServerEntity;
import cn.mumzone.pos.model.ServerTimeTableEntity;
import cn.mumzone.pos.ui.activity.ACT_AddServe;
import cn.mumzone.pos.ui.activity.ACT_OpenOrder;
import cn.mumzone.pos.ui.activity.ACT_ReserveDetail;
import cn.mumzone.pos.ui.widgets.DashView;
import cn.mumzone.pos.ui.widgets.PanelAdapter;
import cn.mumzone.pos.ui.widgets.TrianglePointView;
import cn.mumzone.pos.util.AppUtil;

/**
 * Created by qiuzhenhuan on 2019/6/18.
 */

public class ADA_ReserveInfo extends PanelAdapter {

    private static final int TITLE_TYPE = 4;
    private static final int SERVER_TYPE = 0;
    private static final int TIME_TYPE = 1;
    private static final int RESERVE_TYPE = 2;

    private List<ServerEntity> mServerList = new ArrayList<>();
    private List<ServerTimeTableEntity.ShopBusinessHoursBean> mTimeList = new ArrayList<>();
    private List<List<ReserveEntity>> mReserveList = new ArrayList<>();

    private Context mContext;
    private int offsetSize;
    private long startTime;
    private long triangleOffsetTime, offsetTime;
    private boolean isToday = false;
    private int currentDays = 0;
    private int currentTimePosition = 0;

    public ADA_ReserveInfo(Context context) {
        this.mContext = context;
        offsetSize = DisplayUtil.dip2px(mContext, 20);
        startTime = System.currentTimeMillis();
        float tempOffset = offsetSize + (DisplayUtil.dip2px(mContext, 13) / 2f);
        offsetTime = (long) (BigDecimalUtil.div(Float.toString(tempOffset), Integer.toString(DisplayUtil.dip2px(mContext, 153))) * 30 * 60 * 1000);
        triangleOffsetTime = (long) (BigDecimalUtil.div(Integer.toString(DisplayUtil.dip2px(mContext, 13)), Integer.toString(DisplayUtil.dip2px(mContext, 153))) * 30 * 60 * 1000);
    }

    public void setIsToday(boolean tof) {
        isToday = tof;
        startTime = System.currentTimeMillis();
    }

    public void setDaysPosition(int days) {
        currentDays = days;
    }

    @Override
    public int getRowCount() {
        return mServerList.size() + 1;
    }

    @Override
    public int getColumnCount() {
        return mTimeList.size() + 1;
    }

    @Override
    public int getCurrentTimePosition() {
        int i = 0;
        for (ServerTimeTableEntity.ShopBusinessHoursBean time : mTimeList) {
            if (time.isIsEnable()) {
                return isToday ? i : 0;
            }
            i++;
        }
        return 0;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int row, int column) {
        int viewType = getItemViewType(row, column);
        switch (viewType) {
            case TIME_TYPE:
                setTimeView(column, (TimeViewHolder) holder);
                break;
            case SERVER_TYPE:
                setServerView(row, (ServerViewHolder) holder);
                break;
            case RESERVE_TYPE:
                setReserveView(row, column, (ReserveViewHolder) holder);
                break;
            case TITLE_TYPE:
                break;
            default:
                setReserveView(row, column, (ReserveViewHolder) holder);
        }
    }

    public int getItemViewType(int row, int column) {
        if (column == 0 && row == 0) {
            return TITLE_TYPE;
        }
        if (column == 0) {
            return SERVER_TYPE;
        }
        if (row == 0) {
            return TIME_TYPE;
        }
        return RESERVE_TYPE;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case TIME_TYPE:
                return new TimeViewHolder(LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_panel_time_row, parent, false));
            case SERVER_TYPE:
                return new ServerViewHolder(LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_panel_server_row, parent, false));
            case RESERVE_TYPE:
                return new ReserveViewHolder(LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_panel_reserve_row, parent, false));
            case TITLE_TYPE:
                return new TitleViewHolder(LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_panel_title, parent, false));
            default:
                break;
        }
        return new ReserveViewHolder(LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_panel_reserve_row, parent, false));
    }


    private void setTimeView(int pos, TimeViewHolder viewHolder) {
        String time = mTimeList.get(pos - 1).getMinuteName();
        viewHolder.tvTime.setText(time);
        if ((pos - 1) % 2 == 0) {
            viewHolder.tvTime.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        } else {
            viewHolder.tvTime.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        }
        if (pos == mTimeList.size()) {
            viewHolder.llRoot.setLayoutParams(new RecyclerView.LayoutParams(DisplayUtil.dip2px(mContext, 173), DisplayUtil.dip2px(mContext, 73)));
        } else {
            viewHolder.llRoot.setLayoutParams(new RecyclerView.LayoutParams(DisplayUtil.dip2px(mContext, 153), DisplayUtil.dip2px(mContext, 73)));
        }

        long diffTime = getTimeLinePassTime(mTimeList.get(pos - 1).getMinuteName());
        if (diffTime > 0 && diffTime < (60 * 1000 * 30) + triangleOffsetTime + isLastItem(pos, viewHolder.ivIndicator)) { //差值为30min，在本单元格内
            viewHolder.ivIndicator.setDrawingTriangle(true);
            float scale = BigDecimalUtil.divRetrunFloat(String.valueOf(diffTime), String.valueOf((60 * 1000 * 30) + triangleOffsetTime));
            viewHolder.ivIndicator.setPercent(scale * 100);
        } else {
            viewHolder.ivIndicator.setDrawingTriangle(false);
        }
        if (isToday) {
            viewHolder.ivIndicator.setVisibility(View.VISIBLE);
        } else {
            viewHolder.ivIndicator.setVisibility(View.GONE);
        }
    }

    private long isLastItem(int pos, TrianglePointView view) {

        if (mTimeList.size() == pos) {
            view.setIsEnd(true);
            return (long) (BigDecimalUtil.div(Integer.toString(offsetSize), Integer.toString(DisplayUtil.dip2px(mContext, 153))) * 30 * 60 * 1000);
        }
        return 0;
    }

    private void setServerView(int pos, ServerViewHolder viewHolder) {

        viewHolder.tvServerName.setText(mServerList.get(pos - 1).getTechnicianName());
        viewHolder.tvServerLabel.setText(mServerList.get(pos - 1).getTechnicianLabel());
        viewHolder.tvServeCount.setText(mServerList.get(pos - 1).getServiceCount());
    }

    private void setReserveView(final int row, final int column, ReserveViewHolder viewHolder) {
        final ReserveEntity reserveEntity = mReserveList.get(row - 1).get(column - 1);
        if (reserveEntity != null) {
            viewHolder.viewStatusLine.setVisibility((reserveEntity.getStatus() == ReserveEntity.STATUS_BLANK || reserveEntity.getStatus() == ReserveEntity.STATUS_NOT_IN_WORK) ? View.INVISIBLE : View.VISIBLE);
            viewHolder.tvServiceName.setText((reserveEntity.getStatus() == ReserveEntity.STATUS_BLANK || reserveEntity.getStatus() == ReserveEntity.STATUS_NOT_IN_WORK) ? "" : reserveEntity.getServiceName());
            viewHolder.tvServiceTime.setText((reserveEntity.getStatus() == ReserveEntity.STATUS_BLANK || reserveEntity.getStatus() == ReserveEntity.STATUS_NOT_IN_WORK) ? "" : reserveEntity.getServiceTime());
            viewHolder.viewCutlineLeft.setVisibility(column == 1 ? View.INVISIBLE : View.VISIBLE);

//            if (!mTimeList.get(column - 1).isIsEnable()) {
//                viewHolder.rlRoot.setEnabled(false);
//            } else {
//                viewHolder.rlRoot.setEnabled(true);
//            }
            final boolean clickable = mTimeList.get(column - 1).isIsEnable();

            long diffTime = getPassTime(mTimeList.get(column - 1).getMinuteName());
            if (diffTime > 0 && diffTime < 60 * 1000 * 30) { //差值为30min，在本单元格内
                currentTimePosition = column;
                viewHolder.viewTimeIndicator.setVisibility(View.VISIBLE);
                int maxWidth = DisplayUtil.dip2px(mContext, 153);
                double scale = BigDecimalUtil.div(String.valueOf(diffTime), String.valueOf(60 * 1000 * 30));
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewHolder.viewTimeIndicator.getLayoutParams();
                params.leftMargin = (int) (maxWidth * scale);
                viewHolder.viewTimeIndicator.setLayoutParams(params);
                if (isToday) {
                    viewHolder.viewTimeIndicator.setVisibility(View.VISIBLE);
                } else {
                    viewHolder.viewTimeIndicator.setVisibility(View.GONE);
                }
            } else {
                viewHolder.viewTimeIndicator.setVisibility(View.GONE);
            }

            int statusColor = R.color.title_text_color;
            if (reserveEntity.getStatus() == ReserveEntity.STATUS_BLANK) {
                viewHolder.rlRoot.setBackgroundResource(R.color.white_color);
                statusColor = R.color.title_text_color;
                if (!clickable) {
                    viewHolder.rlRoot.setBackgroundResource(R.color.reserve_unable);
                }
            } else if (reserveEntity.getStatus() == ReserveEntity.STATUS_SERVICE) {
                viewHolder.rlRoot.setBackgroundResource(R.color.order_status_service_bg);
                viewHolder.viewStatusLine.setBackgroundResource(R.color.order_status_service);
                statusColor = R.color.order_status_service;
                viewHolder.rlRoot.setEnabled(true);
            } else if (reserveEntity.getStatus() == ReserveEntity.STATUS_RESERVE) {
                viewHolder.rlRoot.setBackgroundResource(R.color.order_status_reserve_bg);
                viewHolder.viewStatusLine.setBackgroundResource(R.color.order_status_reserve);
                statusColor = R.color.order_status_reserve;
                viewHolder.rlRoot.setEnabled(true);
            } else if (reserveEntity.getStatus() == ReserveEntity.STATUS_NOT_IN_WORK) {
                viewHolder.rlRoot.setBackgroundResource(R.color.reserve_unable);
                statusColor = R.color.title_text_color;
            }
            if (reserveEntity.getStatus() != ReserveEntity.STATUS_BLANK && reserveEntity.getStatus() != ReserveEntity.STATUS_NOT_IN_WORK) {
                if (column - 1 > 0) {
                    ReserveEntity lastReserve = mReserveList.get(row - 1).get(column - 2);
                    if (!StringUtils.isEmpty(lastReserve.getId()) && lastReserve.getId().equals(reserveEntity.getId()) && lastReserve.getStatus() == reserveEntity.getStatus()) {
                        viewHolder.viewStatusLine.setVisibility(View.INVISIBLE);
                        viewHolder.tvServiceName.setText("");
                        viewHolder.tvServiceTime.setText("");
                    } else {
                        viewHolder.viewStatusLine.setVisibility(View.VISIBLE);
                    }
                }
            }
            viewHolder.tvServiceName.setTextColor(mContext.getResources().getColor(statusColor));
            viewHolder.tvServiceTime.setTextColor(mContext.getResources().getColor(statusColor));
            viewHolder.rlRoot.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (reserveEntity.getStatus()) {
                        case ReserveEntity.STATUS_BLANK:
                            if (clickable) {
                                Calendar calendar = Calendar.getInstance();
                                calendar.add(Calendar.DAY_OF_MONTH, currentDays);
                                String str = AppDateUtil.getTimeStamp(calendar.getTime().getTime(), AppDateUtil.YYYY_MM_DD) + " " +
                                        mTimeList.get(column - 1).getMinuteName();
                                String nextServiceStartTime = AppDateUtil.getTimeStamp(calendar.getTime().getTime(), AppDateUtil.YYYY_MM_DD) + " "
                                        + getNextServiceStartTime(column <= mReserveList.get(row - 1).size() ? column : column - 1, row - 1);
                                ACT_AddServe.startAc(mContext,
                                        str, nextServiceStartTime,
                                        mServerList.get(row - 1).getTechnicianLabel(),
                                        reserveEntity.getServerName(),
                                        reserveEntity.getServerId(), currentDays);
                            } else {
                                PosToast.INSTANCE.makeShortToast(mContext, "过点了，不可预约~");
                            }
                            break;
                        case ReserveEntity.STATUS_RESERVE:
                            ACT_OpenOrder.startAc(mContext, AppUtil.hasServiceBusiness() ?
                                    reserveEntity.getAppointmentId() : reserveEntity.getOrderSubId());
                            break;
                        case ReserveEntity.STATUS_SERVICE:
                            if (AppUtil.hasServiceBusiness()) {
                                ACT_OpenOrder.startAc(mContext, reserveEntity.getAppointmentId());
                            } else {
                                ACT_ReserveDetail.startAc(mContext, reserveEntity.getOrderSubId());
                            }
                            break;
                        case ReserveEntity.STATUS_NOT_IN_WORK:
                            if (clickable) {
                                PosToast.INSTANCE.makeShortToast(mContext, "当前时间该技师无排班");
                            } else {
                                PosToast.INSTANCE.makeShortToast(mContext, "过点了，不可预约");

                            }
                            break;
                    }
                }
            });


//            if (orderInfo.getStatus() != OrderInfo.Status.BLANK) {
//                viewHolder.itemView.setClickable(true);
//                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        if (orderInfo.isBegin()) {
//                            Toast.makeText(v.getContext(), "name:" + orderInfo.getGuestName(), Toast.LENGTH_SHORT).show();
//                        } else {
//                            int i = 2;
//                            while (column - i >= 0 && mReserveList.get(row - 1).get(column - i).getId() == orderInfo.getId()) {
//                                i++;
//                            }
//                            final OrderInfo info = mReserveList.get(row - 1).get(column - i + 1);
//                            Toast.makeText(v.getContext(), "name:" + info.getGuestName(), Toast.LENGTH_SHORT).show();
//                        }
//                    }
//                });
//            } else {
//                viewHolder.itemView.setClickable(false);
//            }
        }
    }

    private long getPassTime(String time) {
        String nowDay = AppDateUtil.getTimeStamp(startTime, AppDateUtil.YYYY_MM_DD);
        long currentTime = AppDateUtil.getStringToDate(String.format("%s %s", nowDay, time), AppDateUtil.YYYY_MM_DD_HH_MM);
        return startTime - currentTime;
    }

    private long getTimeLinePassTime(String time) {
        String nowDay = AppDateUtil.getTimeStamp(startTime, AppDateUtil.YYYY_MM_DD);
        long currentTime = AppDateUtil.getStringToDate(String.format("%s %s", nowDay, time), AppDateUtil.YYYY_MM_DD_HH_MM);
        return startTime - (currentTime - offsetTime);
    }


    static class TimeViewHolder extends RecyclerView.ViewHolder {
        TextView tvTime;
        RelativeLayout llRoot;
        TrianglePointView ivIndicator;

        public TimeViewHolder(View itemView) {
            super(itemView);
            this.tvTime = itemView.findViewById(R.id.tv_time);
            this.llRoot = itemView.findViewById(R.id.ll_root);
            this.ivIndicator = itemView.findViewById(R.id.iv_indicator);
        }

    }

    private static class ServerViewHolder extends RecyclerView.ViewHolder {
        TextView tvServerName;
        TextView tvServerLabel;
        TextView tvServeCount;

        public ServerViewHolder(View view) {
            super(view);
            this.tvServerName = view.findViewById(R.id.server_name);
            this.tvServerLabel = view.findViewById(R.id.server_title);
            this.tvServeCount = view.findViewById(R.id.server_count);
        }
    }

    private static class ReserveViewHolder extends RecyclerView.ViewHolder {
        RelativeLayout rlRoot;
        View viewStatusLine;
        DashView viewCutlineLeft;
        View viewTimeIndicator;
        TextView tvServiceName;
        TextView tvServiceTime;

        public ReserveViewHolder(View view) {
            super(view);
            this.rlRoot = view.findViewById(R.id.rl_root);
            this.viewStatusLine = view.findViewById(R.id.view_status_line);
            this.viewCutlineLeft = view.findViewById(R.id.view_cutline_left);
            this.viewTimeIndicator = view.findViewById(R.id.view_time_indicator);
            this.tvServiceName = view.findViewById(R.id.tv_service_name);
            this.tvServiceTime = view.findViewById(R.id.tv_service_time);
        }
    }

    private static class TitleViewHolder extends RecyclerView.ViewHolder {
        TextView titleTextView;

        public TitleViewHolder(View view) {
            super(view);
            this.titleTextView = view.findViewById(R.id.title);
        }
    }


    public void setServerList(List<ServerEntity> serverList) {
        this.mServerList = serverList;
    }


    public void setTimeList(List<ServerTimeTableEntity.ShopBusinessHoursBean> timeList) {
        this.mTimeList = timeList;
    }

    public void setReserveList(List<List<ReserveEntity>> mReserveList) {
        this.mReserveList = mReserveList;
    }

    private String getNextServiceStartTime(int currentPosition, int row) {
        List<ReserveEntity> tempList = mReserveList.get(row);
        for (int i = currentPosition; i < mReserveList.get(row).size(); i++) {
            if (tempList.get(i).getStatus() != ReserveEntity.STATUS_BLANK) {
                return mTimeList.get(i).getMinuteName();
//                return mReserveList.get(row).get(i).getStartTime();
            }
        }
        return mTimeList.get(mTimeList.size() - 1).getMinuteName();
    }
}
